package org.springblade.pm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.pm.entity.*;
import org.springblade.pm.service.IFileService;
import org.springblade.pm.service.IXmglProjectService;
import org.springblade.pm.vo.PageQuery;
import org.springblade.pm.vo.XmglProjectVo;
import org.springblade.pm.wrappper.XmglProjectWrapper;
import org.springblade.system.feign.IDictClient;
import org.springblade.system.feign.ISysClient;
import org.springblade.system.user.entity.UserInfo;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @Title: XmglProjectController.java
 * @Description: TODO
 */

@RestController
@RequestMapping("xmglproject")
@AllArgsConstructor
public class XmglProjectController extends BladeController {

	private IXmglProjectService xmglProjectService;
	ISysClient sysClient;
	IUserClient userClient;
	IDictClient dictClient;
	private IFileService fileService;
	/**
	 * 获取项目所有项目负责人名称
	 *
	 * @return
	 */
	@GetMapping("/leaderName")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取项目负责人", notes = "获取项目项目负责人")
	public R<List<Map<String, Object>>> getLeader() {
		List<Map<String, Object>> tree = xmglProjectService.getLeader();
		return R.data(tree);
	}


	/**
	 * 获取项目信息
	 *
	 * @return
	 */
	@GetMapping("/project")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取项目信息", notes = "获取项目信息")
	public R<List<XmglProject>> xmglProject(String gsid) {
		List<XmglProject> tree = xmglProjectService.getList(gsid);
		return R.data(tree);
	}

	@GetMapping(value = "/list")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "项目列表", notes = "项目列表")
	public R<IPage<XmglProjectVo>> getXmglList(XmglProject xmglProject, PageQuery pageQuery) {
		IPage<XmglProjectVo> iPage= xmglProjectService.getXmglList(xmglProject, pageQuery);
		return R.data(iPage);
	}

	@GetMapping(value = "/select")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "下拉框选项", notes = "下拉框选项")
	public R<List> getSelect(String type, String param) {
		return R.data(xmglProjectService.getSelect(type, param));
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入xmglProject")
	public R<XmglProjectVo> detail(XmglProject xmglProject) {
		XmglProject detail = xmglProjectService.getOne(Condition.getQueryWrapper(xmglProject));

		return R.data(XmglProjectWrapper.build().entityVO(detail));
	}

	/**
	 * 新增或修改 项目管理项目表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入xmglProject")
	public R submit(@Valid @RequestBody XmglProject xmglProject) {
		//设置项目编号
		Map<String, Object> hashMap = new HashMap<>();
		ZTProject ztProject = new ZTProject();
		R<UserInfo> userInfoR = userClient.userInfo(Long.parseLong(xmglProject.getLeader()));
		String po = "";
		if (userInfoR.isSuccess()) {
			po = userInfoR.getData().getUser().getAccount();
		}
		if (null == xmglProject.getId()) {
			String gsjc, projectTypeCode, code;
			Integer projectCategory;
			if ("1".equals(xmglProject.getGsid())) {
				gsjc = "EF-";
			} else {
				gsjc = "EF-";
			}
			//插入禅道表
			//设置项目时间间隔
			xmglProject.setDays(Long.valueOf(xmglProject.getScheduledEndTime().toEpochDay() - xmglProject.getScheduledStartTime().toEpochDay()).intValue());
			xmglProject.setOrderby(0);
			ztProject.setCatID(0);
			ztProject.setName(xmglProject.getName());
			ztProject.setCode(xmglProject.getCode());
			ztProject.setBegin(xmglProject.getScheduledStartTime());
			ztProject.setEnd(xmglProject.getScheduledEndTime());
			ztProject.setDays(xmglProject.getDays());
			ztProject.setPm(po);
			ztProject.setPo(po);
			//待修改
			ztProject.setStatus("doing");
			ztProject.setDesc(xmglProject.getProjectDescribe());
			ztProject.setOpenedBy(this.getUser().getRoleName());
			ztProject.setOpenedDate(LocalDateTime.now());
			ztProject.setOpenedVersion("1");
			ztProject.setClosedDate(LocalDateTime.now());
			ztProject.setCanceledDate(LocalDateTime.now());
			ztProject.setTeam(xmglProject.getName());
			ztProject.setWhitelist("1");
			ztProject.setOrder(xmglProject.getOrderby());
//			ztProject.setDeptId(Integer.parseInt(xmglProject.getDeptId()));
			//添加真正项目
			ZTProduct ztProduct = new ZTProduct();
			ztProduct.setName(xmglProject.getName());
			ztProduct.setCode(xmglProject.getCode());
			ztProduct.setLine(0);
			ztProduct.setDesc("");
			ztProduct.setPo(po);
			ztProduct.setQd("");
			ztProduct.setRd("");
			ztProduct.setWhitelist("");
			ztProduct.setCreatedBy(this.getUser().getRoleName());
			ztProduct.setCreatedDate(LocalDateTime.now());
			ztProduct.setOrder(0);
			ztProduct.setCreatedVersion("1.0");
			ztProduct.setStatus("normal");

			xmglProjectService.saveZTProduct(ztProduct);
			xmglProjectService.saveZT(ztProject);
			//添加中间表
			ZTProjectproduct ztProjectproduct = new ZTProjectproduct();
			ztProjectproduct.setProject(ztProject.getId());
			ztProjectproduct.setProduct(ztProduct.getId());
			ztProjectproduct.setBranch(0);
			ztProjectproduct.setPlan(0);
			xmglProjectService.saveZTProjectproduct(ztProjectproduct);
		} else {
			XmglProject xmglProject1 = xmglProjectService.getById(xmglProject.getId());
			ztProject.setName(xmglProject.getName());
			ztProject.setCode(xmglProject1.getCode());
			ztProject.setBegin(xmglProject.getScheduledStartTime());
			ztProject.setEnd(xmglProject.getScheduledEndTime());
			ztProject.setDays(xmglProject.getDays());
			ztProject.setDesc(xmglProject.getProjectDescribe());
			ztProject.setOpenedBy(this.getUser().getRoleName());
			ztProject.setOpenedDate(LocalDateTime.now());
			ztProject.setClosedDate(LocalDateTime.now());
			ztProject.setCanceledDate(LocalDateTime.now());
			ztProject.setOrder(xmglProject.getOrderby());
			ztProject.setPm(po);
			ztProject.setPo(po);
//			ztProject.setDeptId(Integer.parseInt(xmglProject.getDeptId()));

			ZTProduct ztProduct = new ZTProduct();
			ztProduct.setName(xmglProject.getName());
			ztProduct.setCode(xmglProject1.getCode());
			ztProduct.setLine(0);
			ztProduct.setDesc("");
			ztProduct.setPo(po);
			ztProduct.setQd("");
			ztProduct.setRd("");
			ztProduct.setWhitelist("");
			ztProduct.setCreatedBy(this.getUser().getRoleName());
			ztProduct.setCreatedDate(LocalDateTime.now());
			ztProduct.setOrder(0);
			ztProduct.setStatus("normal");
			xmglProjectService.updateZT(ztProject);
			xmglProjectService.updateZTProduct(ztProduct);
		}
		try {
			/*if (xmglProject.getGsid().equals("1")){
				xmglProject.setSsgs(dictClient.getValue("bx_company",1).getData());
			}else if (xmglProject.getGsid().equals("2")){
				xmglProject.setSsgs(dictClient.getValue("bx_company",2).getData());
			}*/
			xmglProject.setSsgs(sysClient.getTenant(Integer.valueOf(xmglProject.getGsid())).getTenantName());
			xmglProject.setDept(sysClient.getDeptName(Integer.parseInt(xmglProject.getDeptId())));
			xmglProjectService.saveOrUpdate(xmglProject);
			hashMap.put("parentId",xmglProject.getId());
			return R.data(hashMap);
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 事务回滚
			return R.data(hashMap);		}
	}

	/**
	 * 删除 项目管理项目表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		/*List<String> codeList = new ArrayList<>();
		String[] idArray = ids.split(",");
		List<String> idList = Arrays.asList(idArray);
		for (String id : idList) {
			XmglProject xmglProject = xmglProjectService.getById(id);
			if (null != xmglProject) {
				codeList.add(xmglProject.getCode());
			}
		}
		if (codeList.size() != 0) {
			xmglProjectService.deleteBatchCodes(codeList);
		}*/

		List<String> projectIdList = Arrays.asList(ids.split(","));
		for (String projectId:projectIdList){
			QueryWrapper<File> wrapper = new QueryWrapper<>();
			wrapper.eq("parent_id",projectId).eq("module_type","project").select("id");
			List<Map<String, Object>> idList = fileService.listMaps(wrapper);
			List<String> list = new ArrayList<>();
			idList.stream().forEach(map -> list.add(map.get("id").toString()));
			for (String id:list){
				fileService.removeBatchByIds(id);
			}
		}

		return R.status(xmglProjectService.removeByIds(Func.toIntList(ids)));
	}

	/**
	 * 检查code是否为空
	 * @param code
	 * @return
	 */
	@GetMapping("/codeCheck")
	@ApiOperationSupport(order = 8)
	public R codeCheck(String code){
		List<XmglProject> list = xmglProjectService.getXmlgIdByCode(code);
		Map<String, Object> map = new HashMap<>();
		if (list.size()>0){
			map.put("isCode",1);
			return R.data(map);
		}else{
			return R.data(map);
		}
	}
}
